package com.hefan.notify.listener;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.hefan.common.ons.TopicRegistryDev;
import com.hefan.common.ons.TopicRegistryTest;
import com.hefan.live.bean.LivingRoomInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.cat.tiger.util.CollectionUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hefan.common.ons.TopicRegistry;
import com.hefan.common.ons.listener.GLLMessageListener;
import com.hefan.live.itf.LiveRoomService;
import com.hefan.notify.bean.PubParams;
import com.hefan.notify.bean.PushMqVo;
import com.hefan.notify.itf.UmengPushService;
import com.hefan.user.itf.LoginTokenService;

@Component
public class UmengPushListener implements GLLMessageListener {

	Logger logger = LoggerFactory.getLogger(UmengPushListener.class);
	
	@Resource
    LoginTokenService loginTokenService;
	@Resource
    UmengPushService umengPushService;
	@Resource
	LiveRoomService liveRoomService;
	
	@Override
	public TopicRegistry getTopicRegistry() {
		// TODO Auto-generated method stub
		return TopicRegistry.HEFANTV_PUSH;
	}

	@Override
	public TopicRegistryDev getTopicRegistryDev() {
		return TopicRegistryDev.HEFANTV_PUSH_DEV;
	}

	@Override
	public TopicRegistryTest getTopicRegistryTest() {
		return TopicRegistryTest.HEFANTV_PUSH_TEST;
	}

	@Override
	public Action consume(Message message, ConsumeContext context) {
		// TODO Auto-generated method stub
		String realTopic = message.getTag();
		logger.info("umeng push MQ topic: {}, realTopic : {}, msg_body: {}", message.getTopic(), realTopic,
				new String(message.getBody()));
		try {
			Map map = new ObjectMapper().readValue(message.getBody(), Map.class);
			String pushMqVoStr = (String)map.get("pushMqVo");
			PushMqVo pushMqVo = JSON.parseObject(pushMqVoStr, PushMqVo.class);
			Map<String,PubParams> pus = this.dealPushParams(pushMqVo);
			if(pus !=null && !pus.isEmpty()){
				if(pus.containsKey("AND")){
					PubParams andP = pus.get("AND");
					if(andP !=null){
						try {
							this.umengPushService.sendAndroidCustomizedcast(andP);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							logger.error("umeng push安卓队列推送失败");
						}
					}
				}
				if(pus.containsKey("IOS")){
					PubParams andI = pus.get("IOS");
					if(andI !=null){
						try {
							this.umengPushService.sendIOSCustomizedcast(andI);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							logger.error("umeng pushIOS队列推送失败");
						}
					}
				}
			}
			logger.info("umeng push write ok!");
		}catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error("umeng push"+e.getMessage());
			// 失败丢弃
			return Action.CommitMessage;
		}
		logger.info("umeng push complete!");
		return Action.CommitMessage;
	}
	/**
	 * 封装push公共参数
	 * @Title: dealPushParams   
	 * @Description: TODO(这里用一句话描述这个方法的作用)   
	 * @param vo
	 * @return      
	 * @return: PubParams
	 * @author: LiTeng      
	 * @throws 
	 * @date:   2016年10月14日 下午2:45:26
	 */
	private Map<String,PubParams> dealPushParams(PushMqVo vo){
		Map<String,PubParams> reM = new HashMap<String,PubParams>();
		if(vo.type == 1){
			//开播提醒
			reM = this.LiveBeginPush(vo);
			return reM;
		}
		return null;
	}
	/**
	 * 封装开播提醒
	 * @Title: LiveBeginPush   
	 * @Description: TODO(这里用一句话描述这个方法的作用)   
	 * @param vo
	 * @return      
	 * @return: PubParams
	 * @author: LiTeng      
	 * @throws 
	 * @date:   2016年10月14日 下午2:46:09
	 */
	private Map<String,PubParams> LiveBeginPush(PushMqVo vo){
		//获取tokens
		Map<String,PubParams> rel = new HashMap<String,PubParams>();
		if(StringUtils.isBlank(vo.userId)){
			logger.error("umeng push开播提醒推送任务，主播userId出错");
			return null;
		}
		String ticker = "开播提醒";
		String title = "开播提醒";
		String text = "您关注的“"+vo.nickName+"”已经开始直播啦！快来盒饭观看吧！";

	    try {
			//获取device token List
			List<String> deviceTokensList = this.loginTokenService.getLiveRemindUserId(vo.userId);
			if(CollectionUtils.isEmpty(deviceTokensList)){
				return null;
			}
			LivingRoomInfoVo liveMap = vo.getLivingRoomInfoVo();
			//上传文件
			StringBuffer contentBuffer = new StringBuffer();
			logger.info("umeng push"+vo.userId+"开播提醒用户个数："+deviceTokensList.size());
			for (String deviceTokens: deviceTokensList) {
				if(StringUtils.isBlank(deviceTokens)){
					continue;
				}
			    contentBuffer.append(deviceTokens);
			    contentBuffer.append("\n"); // don't forget the return character
			}

			if(StringUtils.isBlank(contentBuffer.toString())){
				return null;
			}
			logger.info("umeng push"+vo.userId+"开播提醒用户列表："+deviceTokensList.toString());
			//and
			try {
				String fileIdAND = this.umengPushService.upLoadTokenFile(contentBuffer.toString(), 1);
				logger.info("umeng push"+vo.userId+"开播提醒AND文件id："+fileIdAND);
				if(StringUtils.isNotBlank(fileIdAND)){
					PubParams pm = new PubParams();
					pm.setTicker(ticker);
					pm.setTitle(title);
					pm.setText(text);
					pm.setFileId(fileIdAND);
					pm.setUpType(1);
					pm.setUpValue(JSONObject.toJSONString(liveMap));
					rel.put("AND", pm);
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				logger.error("umeng push开播提醒AND文件上传失败"+e.getMessage());
			}
			//ios
			try {
				String fileIdIOS = this.umengPushService.upLoadTokenFile(contentBuffer.toString(), 2);
				logger.info("umeng push"+vo.userId+"开播提醒IOS文件id："+fileIdIOS);
				if(StringUtils.isNotBlank(fileIdIOS)){
					PubParams pm = new PubParams();
					pm.setTicker(ticker);
					pm.setTitle(title);
					pm.setText(text);
					pm.setFileId(fileIdIOS);
					pm.setUpType(1);
					pm.setUpValue(JSONObject.toJSONString(liveMap));
					rel.put("IOS", pm);
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				logger.error("umeng push开播提醒IOS文件上传失败"+e.getMessage());
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("umeng push error"+e.getMessage());
			return null;
		}
	    return rel;
	}

}
